package com.bd.scm.module.oauth2;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.SecureRandom;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;

public class HttpUtil {

    public static String httpPost(String url, String data) {
        OutputStreamWriter writer = null;
        BufferedReader reader = null;
        try {
            HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
            if (conn instanceof HttpsURLConnection) {
                SSLContext sc = SSLContext.getInstance("SSL");
                sc.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new SecureRandom());
                ((HttpsURLConnection) conn).setSSLSocketFactory(sc.getSocketFactory());
            }
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Charset", "utf-8");
            if (data.length() > 0) {
                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                writer = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
                writer.write(data);
                writer.flush();
            }
            int rc = conn.getResponseCode();
            String rm = conn.getResponseMessage();
            if (rc == HttpURLConnection.HTTP_OK) {
                reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
                String result = "";
                String line = null;
                while ((line = reader.readLine()) != null) {
                    result += line;
                }
                return result;
            } else {
                throw new Exception(rc + ", " + rm);
            }
        } catch (Exception ex) {
            return ex.getMessage();
        } finally {
            try {
                if (writer != null) {
                    writer.close();
                }
            } catch (Exception ex) {
            }
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (Exception ex) {
            }
        }
    }
}
